﻿//Write a program, that reads from the console an array of N integers and an integer K, sorts the array 
//and using the method Array.BinSearch() finds the largest number in the array which is ≤ K. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04BinarySearchForK
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Size of array:");
            int arraySize = int.Parse(Console.ReadLine());
            Console.Write("Value for K:");
            int k = int.Parse(Console.ReadLine());
            int[] array = new int[arraySize];
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write("array[{0}]:", i);
                array[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("The array you entered looks like this:");
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write("{0} ", array[i]);
            }
            //Sorting:*********************************************************************************************************
            for (int i = 0; i < array.Length - 1; i++)
            {
                for (int j = i + 1; j < array.Length; j++)
                {
                    if (array[i] > array[j])
                    {
                        int temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                    }
                }
            }
            Console.WriteLine("\r\nThe sorted array looks like this:");
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write("{0} ", array[i]);
            }
            int elementIndex = Array.BinarySearch(array, k);
            if (elementIndex >= 0)
            {
                Console.WriteLine("Element = K found at array[{0}]:{1}", elementIndex, array[elementIndex]);
            }
            while (elementIndex < 0)
            {
                k--;
                elementIndex = Array.BinarySearch(array, k);
                if (elementIndex >= 0 )
                {
                    Console.WriteLine("\r\nelement <= K found at array[{0}]:{1}", elementIndex, array[elementIndex]);
                }
            }
            Console.WriteLine("The End!");
            Console.ReadLine();
        }
    }
}
